mod request_id;
mod server_time;
mod auth;

use axum::{Router, handler::Handler, middleware::from_fn};
use tower::{Layer, ServiceBuilder};
use tower_http::{compression::CompressionLayer,
                 LatencyUnit,
                 trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer}};
use tracing::Level;

use request_id::get_request_id;
use server_time::ServerTimeLayer;
use crate::AppState;

pub use auth::verify_token;

pub const REQUEST_ID_HEADER: &'static str = "x-forward-id";
pub const SERVER_TIME_HEADER: &'static str = "x-server-time";

pub(crate) fn set_layer(router: Router) -> Router {
    router.layer(
        ServiceBuilder::new()
            .layer(
                TraceLayer::new_for_http()
                    .make_span_with(DefaultMakeSpan::new().include_headers(true))
                    .on_request(DefaultOnRequest::new().level(Level::INFO))
                    .on_response(DefaultOnResponse::new().level(Level::INFO).latency_unit(LatencyUnit::Micros))
            )
            .layer(
                CompressionLayer::new().gzip(true).br(true).deflate(true)
            )
            .layer(from_fn(get_request_id))
            .layer(ServerTimeLayer)
    )
}